#pragma once
#include <signal.h>
#include <unistd.h> //fork
#include <stdlib.h> //exit
#include <fcntl.h> //open

const char* root_cwd = "/";
const char* dev_null = "dev_null";
void Daemon(bool ischdir, bool isclose)
{
    //1.对信号的屏蔽
    signal(SIGCHLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    //2.创建子进程，退出当前进程
    if(fork() > 0) exit(0);
    
    //3.创建会话
    setsid();

    //4.是否更改为根目录
    if(ischdir)
        chdir(root_cwd);

    //5.重定向012
    if(isclose)
    {
        close(0);
        close(1);
        close(2);
    }
    else
    {
        int fd = open(dev_null, O_RDWR);
        if(fd > 0)
        {
            dup2(fd, 0);
            dup2(fd, 1);
            dup2(fd, 2);
            close(fd);
        }
    }

}